Popular Searches
Popular Course Categories
Popular Courses

Passing Arrays and Objects

Passing Arrays and Objects

Props in React

Passing Arrays and Objects in React

Passing arrays and objects is an important concept in React that allows components to receive and work with structured data through props. Arrays are commonly used to store lists of items, while objects are used to group related information such as student details, product information, and user profiles.

React allows you to pass JavaScript arrays and objects to components using JSX curly braces. The receiving component can access the data through props and use it to display information, perform calculations, or render lists dynamically.

Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Are Props in React?

Props stands for properties. Props are used to pass data from a parent component to a child component. They can contain different JavaScript values, including strings, numbers, arrays, objects, functions, and JSX elements.

For example, a parent component can pass a list of student names as an array or pass a student's name, age, and city together as an object.

function Student({ name, age }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}
function App() {
  return <Student name="Rahul" age={21} />;
}
export default App;

Output:

Rahul
Age: 21

In this example, the parent component passes data through props, and the child component uses the received values.


2. What Is an Array in JavaScript?

An array is a data structure used to store multiple values in a single variable. An array can contain strings, numbers, objects, or other supported JavaScript values.

Example of an Array

const fruits = ["Apple", "Banana", "Mango"];

The array contains three string values. Each item has an index, starting from zero.

Index Value
0 Apple
1 Banana
2 Mango

Arrays are useful when you need to pass multiple related items to a React component, such as product names, course topics, student names, or navigation links.


3. Passing Arrays to React Components

To pass an array to a React component, use curly braces around the array value in JSX.

Syntax

<ComponentName items={arrayName} />

Here, items is the prop name and arrayName is a JavaScript variable containing the array.

Example 1: Passing an Array of Strings

function FruitList({ fruits }) {
  return (
    <div>
      <h2>Fruit List</h2>
      <ul>
        {fruits.map((fruit) => (
          <li key={fruit}>{fruit}</li>
        ))}
      </ul>
    </div>
  );
}
function App() {
  const fruits = ["Apple", "Banana", "Mango"];
  return <FruitList fruits={fruits} />;
}
export default App;

Output:

Fruit List
- Apple
- Banana
- Mango

Explanation:

  • The fruits array stores three fruit names.
  • The parent component passes the array using fruits={fruits}.
  • The child component receives the array through its fruits prop.
  • The map() method creates a list item for every fruit.
  • The key prop helps React identify list items between renders.

Example 2: Passing an Array of Numbers

function NumberList({ numbers }) {
  return (
    <div>
      <h2>Numbers</h2>
      {numbers.map((number) => (
        <p key={number}>{number}</p>
      ))}
    </div>
  );
}
function App() {
  const numbers = [10, 20, 30, 40];
  return <NumberList numbers={numbers} />;
}
export default App;

Output:

Numbers
10
20
30
40

This example demonstrates how a component can receive and display an array of numeric values.

Example 3: Passing an Array Directly

You can pass an array directly inside JSX curly braces without creating a separate variable.

function Skills({ skills }) {
  return (
    <ul>
      {skills.map((skill) => (
        <li key={skill}>{skill}</li>
      ))}
    </ul>
  );
}
function App() {
  return (
    <Skills skills={["HTML", "CSS", "JavaScript", "React"]} />
  );
}
export default App;

Output:

- HTML
- CSS
- JavaScript
- React

This method is convenient for small, fixed arrays. For larger or reusable datasets, keeping the array in a variable can improve readability.


4. What Is an Object in JavaScript?

An object is a data structure that stores information as key-value pairs. Each key identifies a property, and its value contains the associated data.

Example of an Object

const student = {
  name: "Rahul",
  age: 21,
  city: "Mumbai"
};

In this example:

  • name is a property whose value is the string "Rahul".
  • age is a property whose value is the number 21.
  • city is a property whose value is the string "Mumbai".

Objects are useful for representing a single entity with several related properties, such as a student, product, employee, or course.


5. Passing Objects to React Components

To pass an object to a React component, use curly braces around the object variable or object literal.

Syntax

<ComponentName data={objectName} />

Example 1: Passing an Object Through Props

function StudentDetails({ student }) {
  return (
    <div>
      <h2>Student Details</h2>
      <p>Name: {student.name}</p>
      <p>Age: {student.age}</p>
      <p>City: {student.city}</p>
    </div>
  );
}
function App() {
  const student = {
    name: "Priya",
    age: 22,
    city: "Pune"
  };
  return <StudentDetails student={student} />;
}
export default App;

Output:

Student Details
Name: Priya
Age: 22
City: Pune

Explanation:

  • The parent component creates a student object.
  • The object is passed to the child component through student={student}.
  • The child component receives it through the student prop.
  • Individual properties are accessed using dot notation, such as student.name and student.age.

Example 2: Passing an Object Directly

You can also create an object directly inside JSX. The outer curly braces tell JSX to evaluate a JavaScript expression, and the inner braces define the object literal.

function User({ user }) {
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Email: {user.email}</p>
    </div>
  );
}
function App() {
  return (
    <User user={{
      name: "Amit",
      email: "[email protected]"
    }} />
  );
}
export default App;

Output:

Amit
Email: [email protected]

Important: The double curly braces in user={{ ... }} are not a special React syntax. The outer braces represent a JavaScript expression in JSX, and the inner braces create a JavaScript object.

Example 3: Using Object Destructuring

Destructuring lets you extract object properties into variables. You can destructure the object inside the component parameter.

function Employee({ employee }) {
  const { name, role, salary } = employee;
  return (
    <div>
      <h2>{name}</h2>
      <p>Role: {role}</p>
      <p>Salary: ₹{salary}</p>
    </div>
  );
}
function App() {
  const employee = {
    name: "Neha",
    role: "Frontend Developer",
    salary: 50000
  };
  return <Employee employee={employee} />;
}
export default App;

Destructuring can make component code easier to read when working with objects that contain several properties.


6. Passing an Array of Objects in React

An array of objects is a collection of objects stored inside an array. This structure is commonly used when displaying lists of products, students, employees, courses, or blog posts.

Example: Displaying a List of Students

function StudentList({ students }) {
  return (
    <div>
      <h2>Students</h2>
      {students.map((student) => (
        <div key={student.id}>
          <h3>{student.name}</h3>
          <p>Age: {student.age}</p>
          <p>City: {student.city}</p>
        </div>
      ))}
    </div>
  );
}
function App() {
  const students = [
    { id: 1, name: "Aarav", age: 20, city: "Mumbai" },
    { id: 2, name: "Diya", age: 21, city: "Pune" },
    { id: 3, name: "Kabir", age: 22, city: "Delhi" }
  ];
  return <StudentList students={students} />;
}
export default App;

Output:

Students
Aarav
Age: 20
City: Mumbai
Diya
Age: 21
City: Pune
Kabir
Age: 22
City: Delhi

Explanation:

  • The students array contains three objects.
  • Each object represents one student.
  • The array is passed from the parent to the child through props.
  • The map() method iterates through the array and renders each student.
  • The unique id property is used as the React key.

7. Accessing Array and Object Values

Arrays and objects use different methods to access their values.

Data Type Example Access Method Result
Array fruits = ["Apple", "Mango"] fruits[0] Apple
Array numbers = [10, 20, 30] numbers[1] 20
Object student = { name: "Rahul" } student.name Rahul
Object student = { age: 21 } student["age"] 21

Example

function Details({ fruits, student }) {
  return (
    <div>
      <p>First Fruit: {fruits[0]}</p>
      <p>Student Name: {student.name}</p>
    </div>
  );
}
function App() {
  return (
    <Details
      fruits={["Apple", "Mango", "Banana"]}
      student={{ name: "Rahul", age: 21 }}
    />
  );
}
export default App;

Output:

First Fruit: Apple
Student Name: Rahul

8. Passing Arrays and Objects Together

A React component can receive arrays and objects as separate props. This is useful when a component needs both general information and a collection of items.

Example: Course Details and Topics

function Course({ details, topics }) {
  return (
    <div>
      <h2>{details.title}</h2>
      <p>Duration: {details.duration} months</p>
      <p>Level: {details.level}</p>
      <h3>Topics</h3>
      <ul>
        {topics.map((topic) => (
          <li key={topic}>{topic}</li>
        ))}
      </ul>
    </div>
  );
}
function App() {
  const details = {
    title: "React JS Training",
    duration: 3,
    level: "Beginner"
  };
  const topics = ["JSX", "Components", "Props", "State"];
  return <Course details={details} topics={topics} />;
}
export default App;

Output:

React JS Training
Duration: 3 months
Level: Beginner
Topics
- JSX
- Components
- Props
- State

Here, the object contains the course's details, while the array contains the list of topics. Both are passed to the same component through separate props.


9. Difference Between Arrays and Objects

Feature Array Object
Purpose Stores a collection of items Stores related properties as key-value pairs
Syntax [] {}
Access Usually by numeric index Usually by property name
Example ["HTML", "CSS"] { name: "Amit", age: 22 }
Common React use Rendering lists Displaying one item's details
Looping Often uses map() Can use Object.entries() or access known properties

Use an array when you need a collection of items. Use an object when you need to group multiple properties describing one item. You can also combine them, such as an array of product objects.


10. Using map() to Render Arrays in React

The map() method creates a new array by applying a function to every item in an existing array. In React, it is commonly used to transform array data into JSX elements.

Example

function ProductList({ products }) {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name} - ₹{product.price}
        </li>
      ))}
    </ul>
  );
}
function App() {
  const products = [
    { id: 1, name: "Mouse", price: 500 },
    { id: 2, name: "Keyboard", price: 1200 },
    { id: 3, name: "Monitor", price: 8000 }
  ];
  return <ProductList products={products} />;
}
export default App;

Output:

Mouse - ₹500
Keyboard - ₹1200
Monitor - ₹8000

Important: When rendering a list, provide a stable and unique key for each item. A database ID is usually a good choice. Avoid using array indexes as keys when items may be inserted, removed, or reordered.


11. Updating Arrays and Objects Safely

Props should be treated as read-only. If an array or object is received through props, do not directly modify it. When data needs to change, update it in the component that owns the data, often using React state.

Incorrect: Mutating an Object

student.name = "Priya";

This directly changes the existing object. Avoid mutating data that belongs to props or state.

Correct: Creating a New Object

const updatedStudent = {
  ...student,
  name: "Priya"
};

Correct: Creating a New Array

const updatedFruits = [...fruits, "Orange"];

These examples create new arrays or objects rather than modifying the original values. When updating React state, use the appropriate state setter and base updates on the previous state when necessary.

Example: Updating an Array in State

import { useState } from "react";

function FruitApp() {
  const [fruits, setFruits] = useState(["Apple", "Mango"]);

  function addFruit() {
    setFruits((previousFruits) => [
      ...previousFruits,
      "Orange"
    ]);
  }

  return (
    <div>
      <ul>
        {fruits.map((fruit) => (
          <li key={fruit}>{fruit}</li>
        ))}
      </ul>
      <button onClick={addFruit}>Add Fruit</button>
    </div>
  );
}
export default FruitApp;

When the button is clicked, the state setter creates a new array containing the existing fruits and the additional fruit. React can then render the updated list.


12. Common Mistakes When Passing Arrays and Objects

Mistake 1: Forgetting Curly Braces

<FruitList fruits="fruits" />

This passes a string rather than the array stored in a variable. Use:

<FruitList fruits={fruits} />

Mistake 2: Accessing an Object Incorrectly

{student}

Rendering a plain JavaScript object directly as a React child is not supported. Access a property instead, such as {student.name}, or transform the object's data into renderable elements.

Mistake 3: Forgetting the Key in a List

{fruits.map((fruit) => (
  <li>{fruit}</li>
))}

Provide a key so React can identify each list item:

{fruits.map((fruit) => (
  <li key={fruit}>{fruit}</li>
))}

This example is suitable when every fruit value is unique. If duplicates are possible, use a stable unique identifier instead.

Mistake 4: Using the Wrong Property Name

function Student({ student }) {
  return <p>{student.fullName}</p>;
}
const student = { name: "Rahul" };

The example returns no name because the object contains name, not fullName. Use matching property names.

Mistake 5: Mutating Props

Do not directly add, remove, or modify items in an array or object received as props. Keep props read-only and update the data in its owner.

Mistake 6: Assuming Every Value Exists

If a prop is missing or an object property is undefined, accessing nested properties may cause errors. Validate the data or use safe access where appropriate, such as student?.address?.city.


13. Best Practices

  • Use arrays to represent lists of items and objects to represent structured records.
  • Pass arrays and objects using JSX curly braces.
  • Use meaningful prop names, such as students, product, course, and user.
  • Use destructuring to make component parameters and property access easier to read.
  • Use map() to render arrays and provide stable, unique keys.
  • Keep data structures consistent so components can rely on predictable properties.
  • Treat props as read-only and avoid mutating arrays or objects.
  • Use immutable update patterns when changing arrays and objects in state.
  • Handle missing data carefully, especially when working with API responses.
  • Consider TypeScript or validation when a project requires stricter data structure checks.

14. Practical Project: Product List

Build a simple product list that receives an array of product objects and displays the product name, category, and price.

function ProductList({ products }) {
  return (
    <div>
      <h2>Available Products</h2>
      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>Category: {product.category}</p>
          <p>Price: ₹{product.price}</p>
        </div>
      ))}
    </div>
  );
}
function App() {
  const products = [
    { id: 1, name: "Laptop", category: "Electronics", price: 45000 },
    { id: 2, name: "Headphones", category: "Accessories", price: 2000 },
    { id: 3, name: "Keyboard", category: "Accessories", price: 1200 }
  ];
  return <ProductList products={products} />;
}
export default App;

Expected Output:

Available Products
Laptop
Category: Electronics
Price: ₹45000
Headphones
Category: Accessories
Price: ₹2000
Keyboard
Category: Accessories
Price: ₹1200

Learning outcomes:

  • Understand how an array of objects is passed through props.
  • Access object properties inside a child component.
  • Render repeated elements using map().
  • Use unique keys for list items.

15. Interview Questions and Answers

Q1. What is an array in JavaScript?

Answer: An array stores multiple values in an ordered collection, usually accessed by numeric indexes.

Q2. What is an object in JavaScript?

Answer: An object stores related information as key-value pairs.

Q3. How do you pass an array to a React component?

Answer: Use curly braces in JSX, such as .

Q4. How do you pass an object to a React component?

Answer: Pass an object variable or object literal through a prop, such as .

Q5. What is an array of objects?

Answer: It is an array in which each item is an object. It is commonly used to represent collections of products, students, or employees.

Q6. Why is map() used in React?

Answer: The map() method transforms each array item into a result, commonly JSX elements for rendering lists.

Q7. Why is the key prop important?

Answer: A key helps React identify list items across renders and track which items have changed, been added, or been removed.

Q8. Can a component receive an array and an object together?

Answer: Yes. A component can receive multiple props with different data types, including arrays and objects.

Q9. Can props be modified inside a child component?

Answer: No. Props should be treated as read-only. Update the source data in the parent or use state where appropriate.

Q10. What is object destructuring?

Answer: Object destructuring extracts properties from an object into variables, making it easier to work with data.


16. Practice Exercises

  1. Create a FruitList component that receives and displays five fruit names.
  2. Create a StudentDetails component that receives a student object containing name, age, and city.
  3. Create an EmployeeList component that receives an array of employee objects.
  4. Create a Course component that receives a course object and an array of topics.
  5. Create a ProductList component that displays product names and prices using map().
  6. Update an array in React state by adding a new item without mutating the original array.
  7. Display a fallback message when an array is empty.

17. Quick Revision Checklist

  • Understand the purpose of arrays and objects in JavaScript.
  • Know how to pass arrays and objects through React props.
  • Use curly braces when passing JavaScript values in JSX.
  • Access array values using indexes and object values using property names.
  • Use map() to render lists of items.
  • Provide stable and unique keys for list items.
  • Understand how an array of objects can represent structured lists.
  • Use destructuring for readable component code.
  • Avoid mutating props and state directly.

18. Official Documentation and Course Links


Conclusion

Passing arrays and objects in React helps components work with lists and structured information. Arrays are commonly used to render repeated elements, while objects group related properties into one value. By passing them through props, accessing their values correctly, using map() with stable keys, and avoiding direct mutation, you can build reusable and maintainable React applications.

To continue learning React, visit the JustAcademy React JS Training Course or register for a course demo.

whatsapp